iT邦幫忙

2024 iThome 鐵人賽

DAY 7
1
Modern Web

欸你是要進 Vue 了沒?系列 第 7

欸你是要進 Vue 了沒? - Day7:Vue 模板語法【Mustache、v-html】

  • 分享至 

  • xImage
  •  

今天我們正式來學習 Vue 基本的模板語法啦!/images/emoticon/emoticon07.gif

文本插值

使用的是 Mustache 語法,即雙大括號 {{ }}

我們來看看實際例子~

範例

image

Mustache.vue 中,我們可以這樣定義:

<script setup>
const msg = "Mustache message";
</script>

<template>
  <div>{{ msg }}</div>
</template>

而這段程式碼做了以下的事情:

  1. const msg = "Mustache message" 定義了一個名為 msg 的變數,其值為 "Mustache message"
  2. <div>{{ msg }}</div> 使用文本插值的方式,將 msg 屬性的值插入到 HTML 中,這裡會顯示 "Mustache message"

而在它的父組件 App.vue 中,我們可以這樣引入和使用子組件:

<script setup>
import mustache from "./components/Mustache.vue";
</script>

<template>
  <main>
    <mustache />
  </main>
</template>

而這段程式碼做了以下的事情:

  1. 引入子組件:import mustache from Mustache.vueMustache.vue 組件引入,且在這個檔案裡可以用 mustache 來代表引入的該組件。
  2. 使用 <mustache /> 作為自定義標籤,將 Mustache 組件渲染到父組件中。

於是我們在瀏覽器上會看到:
image

原始 HTML

使用的是 v-html 語法。
當我們想要插入「html code」時,可以使用這個方法。

兩者語法差別

{{ }}v-html 不同的地方是:

  • 使用 {{ }} 定義的資料會被以「純文字」渲染。
  • 使用 v-html 屬性定義的值會被以「html code」渲染。

範例

image

我們在 vHtml.vue 這個子組件定義了兩個 div:

  1. <div>{{ rawHtml }}</div>:以 {{ }} 語法定義。
  2. <div v-html="rawHtml"></div>:以 v-html 語法定義。

然後在 App.vue 父組件中將 vHtml 子組件 import 到其中,並指定 rawHtml 屬性值為 "<strong>This is where I can put the HTML code</strong>"

在瀏覽器上會看到:
image
第一行 為:使用 {{ }} 定義的值 >> 被解析成「純文字」。
第二行 為:使用 v-html 定義的值 >> 被解析成「html code」,所以就吃到了我們寫的 strong 粗體樣式(撒花)!!

小結

今天我們先認識最基本的兩種模板語法,明天我們來看看「屬性綁定」
/images/emoticon/emoticon78.gif

範例 code ⬇️

https://github.com/Jamixcs/2024iThome-jamixcs/tree/main/src/components/day7

參考資料


上一篇
欸你是要進 Vue 了沒? - Day6:Vue 專案你是怎麼組起來的?從根組件看組件之間的互動關係
下一篇
欸你是要進 Vue 了沒? - Day8:Vue 模板語法【屬性綁定】
系列文
欸你是要進 Vue 了沒?13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
jeremykuo
iT邦新手 5 級 ‧ 2024-09-21 23:50:12

自動解析內容太酷啦!期待屬性綁定~

++ iT邦新手 5 級 ‧ 2024-09-21 23:56:04 檢舉

/images/emoticon/emoticon06.gif

我要留言

立即登入留言